﻿<template>
  <a-card :bordered="false">
    <div class="table-operator">
      <a-button v-if="hasPerm('Cust_CustomerInfoPotential.Add')" type="primary" icon="plus" @click="handleAdd()"
        >新建</a-button
      >
      <a-button
        v-if="hasPerm('Cust_CustomerInfoPotential.Delete')"
        type="primary"
        icon="minus"
        @click="handleDelete(selectedRowKeys)"
        :disabled="!hasSelected()"
        :loading="loading"
        >删除</a-button
      >
      <!-- <a-button @click="openhtml" type="primary" style="margin-left: 8px">
              <a-icon type="primary" />导出</a-button
            > -->
      <a-button type="primary" icon="redo" @click="getDataList()">刷新</a-button>
      <a-button type="primary" @click="Distribute(selectedRowKeys)">一键分配</a-button>
    </div>

    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="10">
          <a-col :md="4" :sm="24">
            <a-form-item>
              <a-input v-model="queryParam[0].keyword" placeholder="客户名称" />
            </a-form-item>
          </a-col>
          <!-- <a-col :md="4" :sm="24">
            <a-form-item>
              <a-input v-model="queryParam.keyword" placeholder="关键字" />
            </a-form-item>
          </a-col> -->
          <a-col :md="2" :sm="24">
            <a-form-item>
              <a-select
                showSearch
                :filter-option="filterOption"
                v-model="queryParam[1].keyword"
                placeholder="省/直辖市"
                @change="city($event)"
              >
                <a-select-option v-for="(item, dei) in list" :key="item.Id" :value="item.Id">
                  {{ item.Name }}</a-select-option
                >
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="2" :sm="24">
            <a-form-item>
              <a-select
                showSearch
                :filter-option="filterOption"
                v-model="queryParam[2].keyword"
                placeholder="市"
                @change="village($event)"
              >
                <a-select-option v-for="(item, dei) in listChildren" :key="item.Id" :value="item.Id">
                  {{ item.Name }}</a-select-option
                >
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="2" :sm="24">
            <a-form-item>
              <a-select showSearch :filter-option="filterOption" v-model="queryParam[3].keyword" placeholder="选择县级">
                <a-select-option v-for="(item, dei) in county" :key="item.Id" :value="item.Id">
                  {{ item.Name }}</a-select-option
                >
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="14" :sm="24">
            <a-button
              type="primary"
              @click="
                () => {
                  this.pagination.current = 1
                  this.getDataList()
                }
              "
              >查询</a-button
            >
            <a-button style="margin-left: 8px" @click="Repossess">重置</a-button>
            <!-- <div class="dd">
              <a-button @click="visible = true" type="primary">导出数据</a-button>
              <a-button
                style="margin-left: 8px"
                @click="
                  exportExcel($rootUrl + '/CustomerManagement/Cust_CustomerInfoPotential/ExportToExcel', '潜在客户模板')
                "
                ><a-icon type="download" />下载模板</a-button
              >

              <a-upload
                name="file"
                :multiple="true"
                :action="$rootUrl + '/CustomerManagement/Cust_CustomerInfoPotential/Import'"
                :headers="headers"
                @change="handleChange"
              >
                <a-button style="margin-left: 8px"> <a-icon type="upload" />批量导入</a-button>
              </a-upload>
            </div> -->
          </a-col>
        </a-row>
      </a-form>
    </div>
    <a-modal
      title="导出数据"
      :visible="visible"
      :footer="false"
      @cancel="visible = false"
      width="360px"
      style="text-align: center"
    >
      <a-button style="margin: 0 10px" @click="outTab" type="primary">导出当前数据</a-button>
      <a-button @click="openhtml" type="primary" style="margin-left: 8px">
        <a-icon type="primary" />导出所有数据</a-button
      >
    </a-modal>

    <a-table
      id="tables"
      ref="table"
      :scroll="{ y: 530 }"
      :columns="columns"
      :rowKey="(row, index) => row.Id"
      :dataSource="data"
      :pagination="pagination"
      :loading="loading"
      @change="handleTableChange"
      :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange, getCheckboxProps: CheckboxProps }"
      :bordered="true"
      size="small"
    >
      <template slot="AllocationStatus" slot-scope="text, record">
        <a-tag v-if="record.AllocationStatus === 0" @click="Distribute([record.Id])" color="blue">待分配</a-tag>
        <a-tag v-else-if="record.AllocationStatus === 1" @click="Cancel(record)" color="green">已分配</a-tag>
      </template>
      <span slot="CreateTime" slot-scope="CreateTime">{{ timeFormat(CreateTime) }}</span>
      <span slot="action" slot-scope="text, record">
        <template>
          <!-- <a v-if="record.AllocationStatus === 0" @click="Distribute([record.Id])">分配</a>
          <a-divider v-if="record.AllocationStatus === 0" type="vertical" />
          <a v-if="record.AllocationStatus === 1 && hasPerm('Cust_CustomerAllocation.Delete')" @click="Cancel(record)"
            >取消分配</a
          >
          <a-divider v-if="record.AllocationStatus === 1" type="vertical" /> -->
          <a v-if="hasPerm('Cust_CustomerInfoPotential.Edit')" @click="handleEdit(record.Id)">编辑</a>
          <a-divider
            v-if="hasPerm('Cust_CustomerInfoPotential.Edit') && hasPerm('Cust_CustomerInfoPotential.Delete')"
            type="vertical"
          />
          <!-- <a @click="Check(record.Id)">详情</a>
          <a-divider type="vertical" /> -->
          <a v-if="hasPerm('Cust_CustomerInfoPotential.Delete')" @click="handleDelete([record.Id])">删除</a>
          <a-divider v-if="hasPerm('Cust_CustomerInfoPotential.Delete')" type="vertical" />
          <a @click="contactPerson(record)">联系人</a>
        </template>
      </span>
    </a-table>
    <MyCustomer ref="MyCustomer" :IsFormal="IsFormal" :parentObj="this"></MyCustomer>
    <edit-form :disabled="disabled" ref="editForm" :parentObj="this"></edit-form>
    <Check :disabled="disabled" ref="check" :parentObj="this"></Check>
    <List ref="List" />
  </a-card>
</template>

<script>
import List from '../Cust_CustomerLinkMan/List.vue'
//客户分配
import MyCustomer from '../MyCustomer/EditForm.vue'
function exportExcel(res, title) {
  let data = res.data || res || {}

  const blob = new Blob([data], {
    type: 'application/vnd.ms-excel' //设置为excel格式
  })
  const url = window.URL.createObjectURL(blob)
  const fileName = title
  const aTag = document.createElement('a')
  aTag.download = fileName
  aTag.href = url
  aTag.click()
  URL.revokeObjectURL(aTag.href)
  // v.$message.success("导出成功!");
}
import XLSX from 'xlsx'
import FileSaver from 'file-saver'
import Token from '@/utils/cache/TokenCache'
import { download } from '@/components/download'
import EditForm from './EditForm'
import Check from './Check.vue'

import moment from 'moment'
const columns = [
  { title: '客户编码', dataIndex: 'cCusCode', width: '8%' },
  { title: '客户名称', dataIndex: 'cCusName', width: '17%' },

  { title: '电话 ', dataIndex: 'cCusPhone' },
  // { title: '所属行业', dataIndex: 'cTrade' },

  { title: '银行账号 ', dataIndex: 'cCusAccount' },
  { title: '开户银行', dataIndex: 'cCusBank' },
  { title: '地址', dataIndex: 'cCusAddress', ellipsis: true },
  {
    title: '销售经理',
    dataIndex: 'AllocationName',
    align: 'center',
    customRender: value => {
      if (!value) return '无'
      if (value) return value
    }
  },
  {
    title: '分配状态 ',
    dataIndex: 'AllocationStatus',
    align: 'center',
    width: '5%',
    scopedSlots: { customRender: 'AllocationStatus' }
  },
  // { title: '客户级别', dataIndex: 'CustomerKCode' },
  // { title: '备注', dataIndex: 'cMemo' },

  { title: '操作', dataIndex: 'action', align: 'left', scopedSlots: { customRender: 'action' }, width: '15%' }
]

export default {
  components: {
    EditForm,
    MyCustomer,
    Check,
    List
  },
  mounted() {
    this.getDataList()
    this.getlist()
  },
  data() {
    return {
      IsFormal: false,
      headers: {
        authorization: 'Bearer ' + Token.getToken()
      },
      data: [],
      list: [], //省级
      listChildren: [], //市
      county: [], //县
      visible: false,
      disabled: false,
      pagination: {
        current: 1,
        pageSize: 25,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['25', '50', '100'], // 设置pageSize的可选值，页面可以通过下拉框进行选择
        showSizeChanger: true
      },
      filters: {},
      sorter: { field: 'cCusCode', order: 'desc' },
      loading: false,
      columns,
      queryParam: [
        { condition: 'cCusName' },
        { condition: 'cProvince' },
        { condition: 'cCity' },
        { condition: 'cCounty' }
      ],
      selectedRowKeys: []
    }
  },
  methods: {
    contactPerson(row) {
      //console.log(row)

      this.$refs.List.openForm(row, '客户联系人')
    },
    //省市区的模糊查询
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    Cancel(row) {
      var thisObj = this
      this.$confirm('确定取消分配吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return new Promise((resolve, reject) => {
          thisObj.$http
            .post(
              `/CustomerManagement/Cust_CustomerAllocation/DeleteDataForDissolution?CustomerId=${row.Id
              }&& IsFormal= false`
            )
            .then(resJson => {
              resolve()

              if (resJson.Success) {
                thisObj.$message.success('操作成功!')

                thisObj.getDataList()
              } else {
                thisObj.$message.error(resJson.Msg)
              }
            })
        })
      })
      
    },
    Repossess() {
      this.queryParam = [
        { condition: 'cCusName' },
        { condition: 'cProvince' },
        { condition: 'cCity' },
        { condition: 'cCounty' }
      ]
      this.getDataList()
    },
    CheckboxProps(record) {
      return {
        props: {
          disabled: record.AllocationStatus === 1
        }
      }
    },
    //市级change
    city(e) {
      this.$http.post('/Base_BasicData/Base_District/GetDataListByPId?pId=' + e, {}).then(resJson => {
        this.loading = false

        delete this.queryParam[2].keyword
        delete this.queryParam[3].keyword
        this.listChildren = resJson.Data
      })
    },

    //县change
    village(e) {
      this.$http.post('/Base_BasicData/Base_District/GetDataListByPId?pId=' + e, {}).then(resJson => {
        this.loading = false

        this.county = resJson.Data
      })
    },
    //获取省份信息
    getlist(e) {
      this.$http.post('/Base_BasicData/Base_District/GetDataListByPId?pId=0', {}).then(resJson => {
        this.loading = false
        this.list = resJson.Data
      })
    },
    Distribute(row) {
      this.IsFormal = false
      this.$refs.MyCustomer.openForm2(row, '分配客户')
    },
    handleChange(info) {
      if (info.file.status !== 'uploading') {
      }
      if (info.file.status === 'done') {
        if (info.file.response.Success === false) {
          this.$message.error(`${info.file.name}文件,${info.file.response.Msg},请检查文件内容！ `)
        } else {
          this.$message.success(`${info.file.name}  文件上传成功！`)
          this.getDataList()
        }
        this.visible = false
      } else if (info.file.status === 'error') {
        this.$message.error(`${info.file.name} 文件上传失败！`)
      }
    },
    exportExcel(url, tit) {
      download(url, tit)
    },
    outTab() {
      /* generate workbook object from table */
      let wb = XLSX.utils.table_to_book(document.querySelector('#tables'))
      /* get binary string as output */
      let wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
      try {
        FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), '客户联系人.xls')
      } catch (e) {
        if (typeof console !== 'undefined') console.log(e, wbout)
      }
      return wbout
    },
    openhtml() {
      this.$http({
        url: '/CustomerManagement/Cust_CustomerInfoPotential/GetExportList',
        method: 'post',
        data: {
          PageIndex: this.pagination.current,
          PageRows: 999,
          SortField: this.sorter.field || 'Id',
          SortType: this.sorter.order, DeptId: this.DeptId,
          Search: [this.queryParam]
        },
        responseType: 'blob'
      }).then(resJson => {
        exportExcel(resJson, '客户联系人信息')
      })
    },
    handleTableChange(pagination, filters, sorter) {
      this.pagination = { ...pagination }
      this.filters = { ...filters }

      this.getDataList()
    },
    getDataList() {
      this.selectedRowKeys = []

      this.loading = true
      this.$http
        .post('/CustomerManagement/Cust_CustomerInfoPotential/GetDataListByMoreCondition', {
          PageIndex: this.pagination.current,
          PageRows: this.pagination.pageSize,
          SortField: this.sorter.field || 'Id',
          SortType: this.sorter.order, DeptId: this.DeptId,
          Search: this.queryParam,
          ...this.filters
        })
        .then(resJson => {
          this.loading = false
          this.data = resJson.Data
          if (this.data) {
            const pagination = { ...this.pagination }
            pagination.total = resJson.Total
            this.pagination = pagination
          }
        })
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    hasSelected() {
      return this.selectedRowKeys.length > 0
    },
    handleAdd() {
      this.$refs.editForm.openForm(null, '新建客户信息')
    },
    Check(id) {
      this.disabled = true
      this.$refs.check.openForm(id, '查看')
    },
    handleEdit(id) {
      this.disabled = false
      this.$refs.editForm.openForm(id, '编辑客户信息')
    },
    handleDelete(ids) {
      var thisObj = this
      this.$confirm('确认删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return new Promise((resolve, reject) => {
          thisObj.$http.post('/CustomerManagement/Cust_CustomerInfoPotential/DeleteData', ids).then(resJson => {
            resolve()

            if (resJson.Success) {
              thisObj.$message.success('操作成功!')

              thisObj.getDataList()
            } else {
              thisObj.$message.error(resJson.Msg)
            }
          })
        })
      })
    },
    timeFormat(val) {
      // 时间格式化函数
      return moment(val).format('YYYY-MM-DD HH:mm')
    }
  }
}
</script>

<style scoped>
.dd {
  float: right;
}
</style>
